package com.demo2.todo.controller;

import com.demo2.todo.exception.BadRequestException;
import com.demo2.todo.model.dto.CommentRequest;
import com.demo2.todo.model.dto.CommentResponse;
import com.demo2.todo.model.entity.Comment;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.repository.CommentRepository;
import com.demo2.todo.repository.UserRepository;
import com.demo2.todo.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.demo2.todo.utils.SecurityUtils.getCurrentUser;

/**
 * @author evi
 */
@RestController
@RequestMapping("/comments")
@RequiredArgsConstructor
public class CommentController {
    private final CommentService commentService;
    private final CommentRepository commentRepository;
    private final UserRepository userRepository;

    // 获取评论（支持多级）
    @GetMapping("/todo/{todoId}")
    public ResponseEntity<List<CommentResponse>> getCommentsByTodoId(@PathVariable Long todoId) {
        // 先获取一级评论
        List<Comment> rootComments = commentRepository.findByTodoIdAndParentIdIsNull(todoId);

        // 构建评论树
        List<CommentResponse> responses = rootComments.stream()
                .map(comment -> buildCommentTree(comment))
                .collect(Collectors.toList());

        return ResponseEntity.ok(responses);
    }

    // 递归构建评论树
    private CommentResponse buildCommentTree(Comment comment) {
        CommentResponse response = mapToDto(comment);

        // 获取子评论
        List<Comment> children = commentRepository.findByParentId(comment.getId());
        if (!children.isEmpty()) {
            response.setChildren(children.stream()
                    .map(this::buildCommentTree)
                    .collect(Collectors.toList()));
        }

        return response;
    }


    // 创建评论（支持回复）
    @PostMapping
    public ResponseEntity<CommentResponse> createComment(@RequestBody CommentRequest request) {
        User user = getCurrentUser();

        // 检查用户是否被拉黑
        if (!user.isEnabled()) {
            throw new BadRequestException("您已被拉黑，无法评论");
        }

        Comment comment = new Comment();
        comment.setContent(request.getContent());
        comment.setTodoId(request.getTodoId());
        comment.setUserId(user.getId());
        comment.setParentId(request.getParentId());

        Comment saved = commentRepository.save(comment);
        return ResponseEntity.status(HttpStatus.CREATED).body(mapToDto(saved));
    }

    // 在CommentController中添加映射方法
    private CommentResponse mapToDto(Comment comment) {
        CommentResponse response = new CommentResponse();
        response.setId(comment.getId());
        response.setContent(comment.getContent());
        response.setUserId(comment.getUserId());
        response.setTodoId(comment.getTodoId());
        response.setParentId(comment.getParentId());
        response.setCreatedAt(comment.getCreatedAt());
// 添加用户名
        if (comment.getUserId() != null) {
            response.setUsername(userRepository.findUsernameById(comment.getUserId()));
        }
        // 递归处理子评论（如果需要在同一方法中构建完整评论树）
        if (comment.getChildren() != null && !comment.getChildren().isEmpty()) {
            response.setChildren(comment.getChildren().stream()
                    .map(this::mapToDto)
                    .collect(Collectors.toList()));
        }

        return response;
    }
}